# ** Header **
import config
from config import settings
from backend.expose import exposed

import cherrypy
import MySQLdb

# ** Body **
def connect(threadIndex=0, return_object=False):
    if return_object:
        return MySQLdb.connect(config.MYSQL_HOST, config.MYSQL_USER, \
          config.MYSQL_PASSWORD, config.MYSQL_DATABASE)
    else:
        cherrypy.thread_data.db = MySQLdb.connect(config.MYSQL_HOST, config.MYSQL_USER, \
          config.MYSQL_PASSWORD, config.MYSQL_DATABASE)

def collectSettings(threaded=False):
    """
        Reads settings from MySQL table and puts them into an
        internal dictionary to decrease the database load.
        You'll find the entries in config.settings.
        Set threaded=True if you call this method from a CherryPy
        thread (HTTP request).
    """
    if threaded:
        sql = SQLQuery()
        sql.query("SELECT * FROM itf_config")
        sql.close()
        for key, value in sql.res:
            settings.update({key: value})
    else:
        sql = connect(return_object=True).cursor()
        res = sql.execute("SELECT * FROM itf_config")
        for key, value in sql.fetchall():
            settings.update({key: value})
        sql.close()


class SQLQuery:
    """
        A small wrapper for the MySQLdb module
    """
    def __init__(self):
        self.sql = cherrypy.thread_data.db.cursor()
        self.res = None

    def close(self):
        return self.sql.close()

    def query(self, command, multiple=False):
        self.sql.execute(command)
        if multiple:
            self.res = self.sql.fetchall()
        else:
            self.res = self.sql.fetchone()


class DBTest:
    """
        @@cherrypy
        Connects to the configured MySQL database and returns some sample
        data if the connect was successful.
    """ 
    __mount_point__ = "/dbtest"
    __metaclass__ = exposed

    def index(self):
        yield "<html>\n<body>"
        sql = SQLQuery()
        sql.query("SELECT COUNT(*) FROM itf_config")
        sql.close()
        yield "Found %d entries in the MySQL config table.<p />\n" % sql.res[0]

        sql = SQLQuery()
        sql.query("SELECT * FROM itf_config", multiple=True)
        sql.close()
        yield "<table border=1>\n"
        yield "<tr><td><b>Key</b></td><td><b>Value</b></td></tr>\n"
        for key, value in sql.res:
            yield "<tr><td>%s</td><td>%s</td></tr>\n" % (key, value)

        yield "</table>\n</body>\n</html>"

# ** Footer **
